<template>
<div class="problem-case">
    <el-page-header style="font-size: 75%;" @back="goBack" :content="$t('problemMode.case.index')" :title="$t('problemMode.case.goBack')"></el-page-header>

    <div class="case-text">
        <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column type="expand">
            <template slot-scope="props">
                <el-form  class="demo-table-expand" :model="props.row" label-width="120px" style="font-size: 80%;">
                    <el-form-item label="ID" style="display: none;">
                        <span>{{ props.row.id }}</span>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.id')" style="display: none;">
                        <span>{{ props.row.problemId }}</span>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.case.form.addType')"  style="width: 500px;">
                        <el-radio-group v-model="props.row.type">
                        <el-radio :label="0">{{$t('problemMode.case.form.addType0')}}</el-radio>
                        <el-radio :label="1" >{{$t('problemMode.case.form.addType1')}}</el-radio>
                        </el-radio-group>
                      <br/>
                      <span v-if="problemDetail.mode==1" style="color: red;font-size: 90%;">该题目为交互判题，需填写输出数据，实际不参与评测</span>
                    </el-form-item>

                    <el-form-item :label="$t('problemMode.case.form.selectInputFile')" v-show="props.row.type==1" >
                        <el-button size="medium" @click="$refs.fileInput.click()">{{inputFileName}}</el-button>
                        <!-- <el-input v-model="inputFile" placeholder="请输入内容" type="file" style="width:230px;"></el-input> -->
                        <input type="file" ref="fileInput" accept="*" @change="getInputFile" style="display: none">
                        <span style="margin-left: 10px;color: #bfbfbfbf;">文件ID：{{ props.row.inputFileId }}</span>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.case.form.selectOutputFile')" v-show="props.row.type==1" >
                        <el-button size="medium" @click="$refs.fileOutput.click()">{{outputFileName}}</el-button>
                        <!-- <el-input v-model="inputFile" placeholder="请输入内容" type="file" style="width:230px;"></el-input> -->
                        <input type="file" ref="fileOutput" accept="*" @change="getOutputFile" style="display: none">
                         <span style="margin-left: 10px;color: #bfbfbfbf">文件ID：{{ props.row.outputFileId }}</span>
                    </el-form-item>

                    <el-form-item :label="$t('problemMode.case.form.inputData')" v-show="props.row.type==0">
                        <el-input v-model="props.row.input" placeholder="" type="textarea"
                        style="width:49%;" :maxlength="500" show-word-limit :autosize="{ minRows: 7, maxRows: 17}"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.case.form.outputData')" v-show="props.row.type==0" >
                        <el-input v-model="props.row.output" placeholder="" type="textarea"
                        style="width:49%;" :maxlength="500" show-word-limit :autosize="{ minRows: 7, maxRows: 17}"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.case.form.status')">
                        <el-radio-group v-model="props.row.status">
                        <el-radio :label="0">{{ $t('problemMode.case.form.status0') }}</el-radio>
                        <el-radio :label="1" >{{$t('problemMode.case.form.status1')}}</el-radio>
                        </el-radio-group>
                      <span v-show="props.row.type==1" style="font-size: 80%;color: #9f9f9f;">&nbsp;&nbsp;&nbsp;&nbsp;-- 注意：对于文件方式的测试用例，设置为题面样例无效</span>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.case.form.ishow')" >
                        <el-switch v-model="props.row.ishow" :active-value="0" :inactive-value="1"
                        active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                    </el-form-item>
                    <el-form-item :label="$t('problemMode.case.form.description')" v-show="props.row.ishow==0" >
<!--                      <h4 style="text-align: left;margin: 15px;" @click="inputEdit = !inputEdit"><a href="javascript:void(0)">{{ $t('problemMode.save.input') }}</a></h4>-->
                      <mavonEditor :toolbarsFlag = "true"
                                   :subfield = 'false'
                                   ref="md"
                                   v-model="props.row.description"
                                   v-bind="$attrs"
                                   v-on="$listeners"
                                   @imgAdd="handleImgAdd"
                                   style="min-height: 80px;width: 80%;"/>
<!--                        <el-input v-model="props.row.description" placeholder="" type="textarea"  style="width:80%;" :autosize="{ minRows: 7, maxRows: 17}"></el-input>-->
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="saveOrUpdate(props.row)" size="min">{{$t('save')}}</el-button>
                    </el-form-item>
                </el-form>
            </template>
            </el-table-column>
            <el-table-column type="index"  width="50">  </el-table-column>
            <el-table-column :label="$t('problemMode.case.table.type')"
              :formatter="formatterType" >
            </el-table-column>
            <el-table-column :label="$t('problemMode.case.form.status')">
            <template slot-scope="scope" >
                <div v-html="formatterStatus(scope.row.status)"></div>

            </template>
            </el-table-column>
            <el-table-column :label="$t('problemMode.case.table.ishow')">
            <template slot-scope="scope" >
                <div v-html="formatterIShow(scope.row.ishow)"></div>

            </template>
            </el-table-column>
            <el-table-column :label="$t('createTime')"
              :formatter="formatterDate" >
            </el-table-column>
            <el-table-column fixed="right" :label="$t('problemMode.operation.index')" width="220" >
            <template slot-scope="scope">
                <div v-if="scope.row.id">
                  <el-popover
                      placement="top"
                      trigger="click">
                    <el-button type="info" style="width: 100%" plain size="small" @click="lookFileData(scope.row,'.in')">输入样例</el-button>
                    <br/>
                    <el-button type="info" style="width: 100%;margin-top: 10px;" plain size="small" @click="lookFileData(scope.row,'.out')">输出样例</el-button>
                    <el-link v-if="scope.row.type!=0"  type="success"
                             slot="reference"
                             size="small" >{{$t('problemMode.case.table.lookData')}}</el-link>
                  </el-popover>
<!--                    <el-link v-if="scope.row.type!=0"  type="success" @click="lookFileData(scope.row)"  size="small" >{{$t('problemMode.case.table.lookData')}}</el-link>-->
                    <el-link  style="margin-left: 10px;" type="danger" @click="deleteCase(scope.row.id)"  size="small" >{{$t('problemMode.case.table.delete')}}</el-link>
                </div>

                <!-- <el-button @click="update(scope.row)" type="warning" size="small">{{ $t('problemMode.operation.update') }}</el-button> -->
            </template>
        </el-table-column>
        </el-table>
        <!-- 添加 -->
        <el-button type="primary" @click="addCase" style="width:98%;margin-left: 0.5%;margin-top: 10px;" plain> + {{$t('problemMode.case.table.add')}}</el-button>
    </div>

</div>
</template>
<style>
.problem-case .el-table .warning-row {
    background: oldlace;
}


</style>
<script lang="ts">
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import * as problemApi from '@/api/problem'
import {uploadImage} from '@/api/admin'
export default {
    name: 'problemCase',
    components: {
      mavonEditor,
    },
    data() {
        return {
            problemDetail:{},
            tableData:[],
            inputFileName: this.$t('problemMode.case.uploadFileMsg'), //上传文件
            outputFileName: this.$t('problemMode.case.uploadFileMsg'),
            inputFile:null,
            outputFile:null,
            uploadFileFlag1:false,
            uploadFileFlag2:false,
            newData:{
                "problemId":this.$route.query.problemId,
                "type":0,
                "status":0,
                "ishow":1,
                "input":"",
                "output":"",
                "description":""
            },
        };
    },
    methods: {
      //文件方式的case，跳转文档
      lookFileData(item,str){  //查看文件数据
        problemApi.downLoadProblemCase({"problemId":item.problemId,fileId:item.inputFileId+str}).then(res=>{
          var blob = new Blob([res.data], { type: 'text/html' });
          console.info(blob);
          var file = (window.URL || window.webkitURL).createObjectURL(blob);
          window.open(file,"_blank")
        })
      },
      // 将图片上传到服务器，返回地址替换到md中
      async handleImgAdd(pos, file) {
        let form = new FormData();
        form.append('file', file);

        const res = await uploadImage(form).then(res=>{
          return '/api/user/download/'+res.data.data;
        })
        console.log(res);
        this.$refs.md.$img2Url(pos, res);
      },
        //展示行不同颜色
        tableRowClassName({row, rowIndex}) {

            if (!row.createTime) {
                console.info(row.createTime);
                return 'warning-row';
            }
            return '';
        },
        //添加新的按钮
        addCase(){
            this.tableData.push(JSON.parse(JSON.stringify(this.newData)))
        },
        goBack() {
            // console.log('go back');
            this.$router.go(-1);
        },
        //获取题目所有测试用例
        getListcase() {
            problemApi.getProblemCaseList({"id":this.$route.query.problemId}).then(res=>{
                if(res.data.data)this.tableData = res.data.data;
            })
        },
        //获取文件
        getInputFile(event){
            // console.info(event.target.files);
            if(event.target.files[0]&&event.target.files[0].name){
                this.inputFile = event.target.files[0];
                this.inputFileName  = event.target.files[0].name;
                this.uploadFileFlag1 = true;
            }

            // if(event.target.files[1])this.outputFile = event.target.files[1].name;
        },
        getOutputFile(event){

            // console.info(event.target.files);
            if(event.target.files[0]&&event.target.files[0].name){
                this.outputFile = event.target.files[0];
                this.outputFileName  = event.target.files[0].name;
                this.uploadFileFlag2 = true;
            }
            // if(event.target.files[1])this.outputFile = event.target.files[1].name;
        },
        async saveOrUpdate(data){
            //文件数据
                        // &&this.uploadFileFlag2&&this.uploadFileFlag1
            if(data.type==1){
                console.info(data);
                //获取文件
                let form = new FormData();
                form.append('files', this.inputFile);
                form.append('files', this.outputFile);
                form.append("problemId",this.$route.query.problemId)
                //上传文件
                const res = await problemApi.uploadProblemCase(form).then(res1=>{
                    return res1.data.data;
                })
                if(this.isEmpty(res)){  //上传失败，终止保存
                    return ;
                }
                data.outputFileId = res;
                data.inputFileId = res;
                this.inputFile = null;
                this.outputFile = null;
            }

            this.outputFileName = this.$t('problemMode.case.uploadFileMsg');
            this.inputFileName = this.$t('problemMode.case.uploadFileMsg');

            if(!this.isEmpty(data.id)){  //无id 为添加
                problemApi.updateProblemCase(data).then(res=>{
                    // if(res.data.success) this.$router.go(0);  //刷新
                    this.$message({type:"success",message:"修改成功"})
                    this.getListcase();
                });
            }else{   //修改
                problemApi.saveProblemCase(data).then(res=>{
                    // if(res.data.success) this.$router.go(0);  //刷新
                    this.getListcase();
                    this.$message({type:"success",message:"保存成功"})
                });
            }
        },
        deleteCase(id){
            this.$confirm(this.$t('problemMode.case.deleteWarn'), this.$t('prompt'), { confirmButtonText: this.$t('save'), cancelButtonText: this.$t('cancel'), type: 'warning' }).then(() => {
                problemApi.deleteProblemCase({"id":id}).then(res=>{
                    if(res.data.success){
                        this.$message({type: 'success',message: '删除成功!'});
                        this.getListcase();
                    }
                })
            })
        },
        formatterType(data){
            if(data.type==0) return this.$t('problemMode.case.form.addType0');
            else if(data.type==1) return this.$t('problemMode.case.fileExample')
        },
        formatterStatus(type){
            if(type==0)return '<span style="color:green;">'+this.$t('problemMode.case.form.status0')+'</span>';
            else return '<span style="color:grey;">'+this.$t('problemMode.case.form.status1')+'</span>'
        },
        formatterIShow(type){
            if(type==0) return '<span style="color:red;">'+this.$t('problemMode.case.ishow0')+'</span>'
            else return '<span style="color:grey;">'+this.$t('problemMode.case.ishow1')+'</span>'
        },
        formatterDate(data){
            return data.createTime;
        },
        isEmpty(data){
            return (!data)||data=='';
        },
      //获取题目详情
      getById(){
        problemApi.getOneById({"id":this.$route.query.problemId}).then(res=>{
          if(res.data.code==10000){
            this.problemDetail = res.data.data;
            //填入
          }
        })
      },
    },
    created(){
        // console.info(this.$route.query)
        this.getListcase();
      this.getById();
    }


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.problem-case{
    height: 100%;
}
.problem-case .case-text{
    width:98%;
    background-color: #fff;
    margin-top: 10px;
    border-radius: 8px;
    /* margin-right: 45px; */
    /*height: 500px;*/
  padding-bottom: 15px;
}

</style>
